package com.knight.mall.admin.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UrlPathHelper;

import com.knight.mall.admin.page.model.EnterpriseAgent;
import com.knight.mall.admin.page.model.MenuDto;
import com.knight.mall.admin.web.utils.GetMenu;
import com.knight.mall.admin.web.utils.PathUtils;

public class WholeInterceptor implements HandlerInterceptor {
	
	
	private List<String> excludorUrl;
	
	public List<String> getExcludorUrl() {
		return excludorUrl;
	}

	public void setExcludorUrl(List<String> excludorUrl) {
		this.excludorUrl = excludorUrl;
	}

	@Autowired
	private UrlPathHelper urlPathHelper;
	
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WholeInterceptor.class);

	// 在控制器方法调用前执行
	// 返回值为是否中断，true,表示继续执行（下一个拦截器或处理器）
	// false则会中断后续的所有操作，所以我们需要使用response来响应请求
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		//如果是ajax的话返回true
		if(PathUtils.isAjax(request)){
			return true;
		}
		
		String requestPath = urlPathHelper.getPathWithinServletMapping(request);
		
		if(PathUtils.matches(requestPath, excludorUrl)){
			return true;
		}
		
		
		EnterpriseAgent enterpriseAgent = (EnterpriseAgent)request.getSession().getAttribute(EnterpriseAgent.REQUEST_ATTR_NAME);
		
		if(enterpriseAgent==null){
			response.sendRedirect("/");
			return false;
		}
		
		return true;
	}

	// 在控制器方法调用后，解析视图前调用，我们可以对视图和模型做进一步渲染或修改
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		String requestPath = request.getRequestURI();

		if (requestPath != null && !"".equals(requestPath) && !requestPath.contains(".")) {
			String requestUrl = request.getScheme() // 当前链接使用的协议
					+ "://" + request.getServerName()// 服务器地址
					+ ":" + request.getServerPort() // 端口号
					+ request.getContextPath();
			if (modelAndView != null) {
				modelAndView.addObject("appUrl", requestUrl);
			}
			logger.debug("appUrl:{}", requestUrl);
		}
		
		 requestPath = urlPathHelper.getPathWithinServletMapping(request);
		
		if (requestPath != null && !"".equals(requestPath) && !requestPath.contains(".")) {

			List<MenuDto> menus = GetMenu.getMenuS();

			for (MenuDto m : menus) {

				if (requestPath.contains(m.getUrl()) && m.getChildMenus()==null) {
					m.setIsChecked("1");
				}

				if (m.getChildMenus() != null) {
					for (MenuDto child : m.getChildMenus()) {
						if (requestPath.contains(child.getCompareUrl())
								|| child.getCompareUrl().contains(requestPath)) {
							m.setIsChecked("1");
							child.setIsChecked("1");
							if(modelAndView!=null){
								modelAndView.addObject("childMenus", m.getChildMenus());
							}
						}
					}
				}
			}

			if(modelAndView!=null){
				modelAndView.addObject("menus", menus);
			}
		}
		
	}

	// 整个请求完成，即视图渲染结束后调用，这个时候可以做些资源清理工作，或日志记录等
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
	
	
	
}
